package com.tiyende.kash.loop.common

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.LocaleListCompat
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.base.BaseActivity
import com.tiyende.kash.loop.base.app.TiyendeActivityStackManager
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointHelper
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.event.TiyendeEventSubscriber
import com.tiyende.kash.loop.request.HttpHelper
import com.tiyende.kash.loop.request.IHttpCallback
import com.tiyende.kash.loop.request.NetworkRequestManager
import com.tiyende.kash.loop.ui.activity.TiyendeCustomerChatActivity
import com.tiyende.kash.loop.ui.dialog.TiyendeCustomerDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeLanguageDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeTipsDialog
import org.json.JSONObject

/**
 * CommonActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/20 10:32
 * @Annotation：
 */
abstract class CommonActivity: BaseActivity(), TiyendeEventSubscriber,ICommonView {

    private var errorDialog: TiyendeTipsDialog? = null
    var eventRemark: String? = ""

    override fun getAct(): CommonActivity {
        return this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        NetworkRequestManager.registerActivity(this)
        super.onCreate(savedInstanceState)
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.setTag(this)
        TiyendeApp.app.publisher.register(this)
    }

    override fun onResume() {
        super.onResume()
        NetworkRequestManager.onActivityResumed(this)
    }

    override fun initTiyendeListener() {
        //切换语言
        rootViewBinding.rootSwitchLang.setOnClickListener {
            showTiyendeSwitchLanguageDialog(eventRemark,onConfirmCallback = {
            })
        }
        //联系客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventRemark)
        }
    }

    /**
     * 错误提示
     */
    fun showErrorTipsDialog(tips: String,eventRemark: String = ""){
        if (isFinishing || isDestroyed){
            return
        }
        if (errorDialog == null){
            errorDialog = TiyendeTipsDialog(this,eventRemark)
        }
        errorDialog?.let {
            if (it.isShowing){
                return
            }
        }
        errorDialog?.setOnClick(object : TiyendeTipsDialog.IDialogCallback{
            override fun onClick(view: View?) {

            }
        })
        errorDialog?.show()
        errorDialog?.isTiyendeDoubleButton(false)
        errorDialog?.addTiyendeTipsText(tips)
    }

    /**
     * 客服
     */
    fun showCustomerDialog(eventRemark: String? = "",pName: String = "", pToken: String = ""){
        TiyendeCustomerDialog(this)
            .setCustomerCancelable(true)
            .setCustomerCanceledOnTouchOutside(true)
            .setCustomerProductName(pName)
            .setCustomerProductToken(pToken)
            .setCustomerEventRemark(eventRemark)
            .setCustomerClickCallback(object : TiyendeCustomerDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view?.id == R.id.customerChatOnline){
                        if (TiyendeActivityStackManager.isCurrentActivity(TiyendeCustomerChatActivity::class.java)){
                            return
                        }
                        onIntent(TiyendeCustomerChatActivity::class.java)
                    }
                }
            })
            .show()
    }

    /**
     * 切换语言
     */
    fun showTiyendeSwitchLanguageDialog(eventRemark: String?,isCancel: Boolean = true,isCancelTouch: Boolean = true,onConfirmCallback: () -> Unit){
        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_LANGUAGE_SWITCH,eventRemark)
        val dialog = TiyendeLanguageDialog(getContext(),eventRemark,object : TiyendeLanguageDialog.IDialogCallback {
            override fun onLanguageSelectedItem(data: JSONObject) {
                val lang = data.optString("value")
                var appCurtLanguage = ""
                val locale = AppCompatDelegate.getApplicationLocales()[0]
                locale?.let {
                    appCurtLanguage = locale.language
                }
                AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(lang))
                if (appCurtLanguage == lang) {//设置和当前应用语言相同的语言，应用不会重启
                    onConfirmCallback()
                } else {
                    //首次安装appCurtLanguage=“”，防止多次加载启动页
                    if (appCurtLanguage.isNotEmpty()) {
                        // 创建一个指向启动页的 Intent
//                        val intent = Intent(this@ProActivity, LaunchActivity::class.java).apply {
//                            // 添加标志以清除当前任务栈并创建一个新的
//                            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
//                        }
//                        startActivity(intent)
//                        overridePendingTransition(R.anim.fade_in, R.anim.fade_out)
//                        finish()
                        //重建当前页面
                        //recreate()
                    }
                }
                //设置不同类型的语言后，应用会重启，重走时区接口
            }
        })
        dialog.setCancelable(isCancel)
        dialog.setCanceledOnTouchOutside(isCancelTouch)
        dialog.show()
    }

    /**
     * post
     */
    fun doPostAction(httpUrl: String,params: JSONObject,callback: IHttpCallback){
        HttpHelper.post(httpUrl,params,object: IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        callback.onRequestSuccess(data)
                    }
                    else -> {
                        callback.onRequestError(data)
                        val msg = data.optString("msg")
                        showTiyendeToast(msg)
                        hiddenTiyendeLoading()
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                callback.onRequestError(error)
                hiddenTiyendeLoading()
            }

            override fun onRequestFinish() {
                callback.onRequestFinish()
            }
        })
    }

    /**
     * 添加埋点
     */
    fun addEventPointRequestAction(eventName: String, eventRemark: String? = "") {
        TiyendeEventPointHelper.addEventPointRequestAction(eventName,eventRemark)
    }

    /**
     * 发送事件通知
     */
    fun publishEventData(eventData: TiyendeEventData){
        TiyendeApp.app.publisher.publish(eventData)
    }

    /**
     * 处理订阅事件
     */
    override fun onTiyendePublishEvent(event: TiyendeEventData) {
    }

    /**
     * 重试
     */
    override fun requestTryAgain() {
    }

    override fun onDestroy() {
        super.onDestroy()
        NetworkRequestManager.unregisterActivity(this)
        HttpHelper.cancelTag(this)
        TiyendeApp.app.publisher.detach(this)
    }
}